<template>
   <!-- 角色权限 -->
   <div class="container">
      <el-card
         shadow="never"
         style="padding: 0px"
      >
         <CardTitle
            :title="pageTitle"
            :hasBackButton="showBackButton"
         ></CardTitle>
         <el-button
            color="#6860FF"
            style="position: absolute; right: 25px; top: 30px"
            @click.stop="savePermissions"
            >保存</el-button
         >
      </el-card>
      <el-row
         :gutter="0"
         class="full-height-row"
      >
         <!-- 左侧部门树 -->
         <el-col
            :span="4"
            class="full-height-col-left"
         >
            <el-card
               style="background: #f5f8fd; height: 62px"
               shadow="never"
            >
               <div
                  style="display: flex; justify-content: space-between; flex-direction: row; align-items: center"
                  v-if="!isSearch"
               >
                  <div>角色分组</div>
                  <div style="cursor: pointer">
                     <el-icon
                        style="margin-right: 20px"
                        @click.stop="handleSearch"
                     >
                        <Search />
                     </el-icon>
                     <el-icon @click.stop="handleAddRole">
                        <Plus />
                     </el-icon>
                  </div>
               </div>
               <div
                  style="display: flex; justify-content: space-between; flex-direction: row; align-items: center"
                  v-if="isSearch"
               >
                  <el-input
                     ref="inputRef"
                     @blur="isSearch = false"
                     autofocus
                     placeholder="请输入"
                     suffix-icon="Search"
                     v-model="filterText"
                  />
                  <el-icon>
                     <Plus />
                  </el-icon>
               </div>
            </el-card>
            <el-card
               shadow="never"
               class="full-height-card"
               style="overflow-y: scroll"
            >
               <div class="button-container"></div>
               <el-tree
                  highlight-current
                  class="full-height-tree"
                  :data="Array.isArray(departmentTree) ? departmentTree : []"
                  node-key="id"
                  :props="treeProps"
                  accordion
                  @node-click="handleNodeClick"
                  :filter-node-method="filterNode"
                  ref="treeRef"
               >
                  <template #default="scope">
                     <div class="custom-tree-node">
                        <span :class="{ 'disabled-node': scope.node.data.status === 0 }">{{ scope.node.label }}</span>
                        <span class="operation-icons">
                           <el-dropdown
                              trigger="click"
                              @command="handleCommand"
                           >
                              <el-icon class="custom-icon node-tools" @click.stop>
                                 <Tools color="#172B4D" />
                              </el-icon>
                              <template #dropdown>
                                 <el-dropdown-menu @click.stop>
                                    <el-dropdown-item :command="{ type: 'edit', data: scope.node.data }">编辑</el-dropdown-item>
                                    <el-dropdown-item
                                       :command="{ type: 'add', data: scope.node.data }"
                                       v-if="scope.node.data.parent_id === 0"
                                       >新增子集</el-dropdown-item
                                    >
                                    <el-dropdown-item :command="{ type: 'delete', data: scope.node.data }">删除</el-dropdown-item>
                                 </el-dropdown-menu>
                              </template>
                           </el-dropdown>
                        </span>
                     </div>
                  </template>
               </el-tree>
            </el-card>
         </el-col>
         <!-- 右侧表单 -->
         <el-col
            :span="20"
            class="full-height-col-right"
         >
            <el-card
               style="padding: 0px; overflow-y: scroll"
               class="full-height-card"
               shadow="never"
            >
               <div class="mb-4 right-container-title">
                  <el-input
                     style="width: 200px; transform: translateX(10px)"
                     v-model="search"
                     placeholder="菜单"
                     suffix-icon="Search"
                  />
                  <div>
                     <el-button
                        color="#6860FF"
                        @click.stop="selectAll"
                        >全选</el-button
                     >
                     <el-button
                        color="#6860FF"
                        @click.stop="unselectAll"
                        >取消全选</el-button
                     >
                  </div>
               </div>
               <el-card shadow="never">
                  <!-- 表格形式的权限选择 -->
                  <el-table
                     :data="filteredMenuPermissions"
                     border
                     style="width: 100%"
                  >
                     <!-- 第一列：一级菜单 row-key="id"-->
                     <el-table-column
                        label="一级"
                        width="180"
                     >
                        <template #default="scope">
                           <el-checkbox
                              :model-value="isMenuChecked(scope.row)"
                              :indeterminate="isMenuIndeterminate(scope.row)"
                              @change="(val) => handleMenuCheckChange(val, scope.row)"
                              @click.stop
                           >
                              {{ scope.row.name }}
                           </el-checkbox>
                        </template>
                     </el-table-column>

                     <!-- 第二列：二级菜单 -->
                     <el-table-column label="二级">
                        <template #default="scope">
                           <div class="submenu-container">
                              <el-checkbox
                                 v-for="(submenu, submenuIndex) in scope.row.children"
                                 :key="submenuIndex"
                                 :model-value="isSubmenuChecked(submenu)"
                                 :indeterminate="isSubmenuIndeterminate(submenu)"
                                 @change="(val) => handleSubmenuCheckChange(val, submenu)"
                                 @click.stop
                                 class="submenu-checkbox"
                              >
                                 {{ submenu.name }}
                              </el-checkbox>
                           </div>
                        </template>
                     </el-table-column>

                     <!-- 第三列：权限项 -->
                     <el-table-column label="三级">
                        <template #default="scope">
                           <div class="permission-container">
                              <div
                                 v-for="(submenu, submenuIndex) in scope.row.children"
                                 :key="submenuIndex"
                                 class="permission-group"
                              >
                                 <div class="permission-items">
                                    <el-checkbox
                                       v-for="(item, itemIndex) in submenu.children"
                                       :key="itemIndex"
                                       :model-value="item.is_checked === 1"
                                       @update:model-value="(val) => { item.is_checked = val ? 1 : 0; handlePermissionItemChange(submenu); }"
                                       @click.stop
                                       class="permission-checkbox"
                                    >
                                       {{ item.name }}
                                    </el-checkbox>
                                 </div>
                              </div>
                           </div>
                        </template>
                     </el-table-column>
                  </el-table>
               </el-card>
            </el-card>
         </el-col>
      </el-row>
   </div>
   <NewRole
      ref="newRoleRef"
      @getRoleList="getRoleList"
   />
   <EditRole
      ref="editRoleRef"
      @getRoleList="getRoleList"
   />
</template>

<script setup lang="ts">
   import { ref, reactive, computed, watch, nextTick, onMounted } from "vue";
   import CardTitle from "@/components/card-title/CardTitle.vue";
   import NewRole from "./components/newRole.vue";
   import { Plus, Search, Tools } from "@element-plus/icons-vue";
   import { ElMessage, ElMessageBox } from "element-plus";
   import type { TreeInstance } from "element-plus";
   import EditRole from "./components/EditRole.vue";
   import api from "@/api/index.js";
   const showBackButton = false;
   const isSearch = ref<boolean>(false); //是否搜索
   const inputRef = ref();
   const pageTitle = "角色权限";
   const treeProps = {
      children: "children",
      label: "name",
   };
   const editRoleRef = ref();
   const newRoleRef = ref();
   // 获取角色列表
   const getRoleList = async () => {
      const res = await api.authority.getRoleList();
      if (res.code === 200) {
         departmentTree.value = res.data;
      }
   };
   // 当前选中的节点数据
   const currentNode = ref<any>(null);

   // 节点点击处理
   const handleNodeClick = (data: any) => {
      currentNodeId.value = data.id;
      currentNode.value = data;
      console.log("Node clicked:", data);
      getPermissionList();
   };

   // 处理下拉菜单命令
   const handleCommand = (command: any) => {
      if (command.type === "edit") {
         handleEditRole(command.data);
      } else if (command.type === "add") {
         newRoleRef.value.openLoading(command.data.id);
      } else if (command.type === "delete") {
         ElMessageBox.confirm(`确定要删除角色 "${command.data.name}" 吗？`, "删除确认", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
         })
            .then(() => {
               handleDeleteRole(command.data);
            })
            .catch(() => {
               ElMessage({
                  type: "info",
                  message: "已取消删除",
               });
            });
      }
   };

   // 编辑角色
   const handleEditRole = async (role: any) => {
      if (!role) return;
      try {
         console.log("编辑角色:", role.id);
         editRoleRef.value.openLoading(role.id);
      } catch (error) {
         console.error("编辑角色失败:", error);
         ElMessage.error("角色编辑失败");
      }
   };

   // 删除角色
   const handleDeleteRole = async (role: any) => {
      if (!role) return;
      try {
         const res = await api.authority.deleteRole({ id: role.id });
         if (res.code === 200) {
            ElMessage.success("角色删除成功");
            // 重新获取角色列表
            getRoleList();
            // 清空当前选中的节点
            currentNode.value = null;
            currentNodeId.value = null;
            // 清空权限列表
            permissionGroups.value = [];
         } else {
            throw new Error(res.message || "删除失败");
         }
      } catch (error) {
         console.error("删除角色失败:", error);
         ElMessage.error("角色删除失败");
      }
   };

   // 重构后的权限数据结构
   interface Permission {
      name: string;
      checked: boolean;
      id: number;
      auth_code: string;
      paths: string;
   }

   interface PermissionGroup {
      type: number;
      groupName: string;
      auth_code: string;
      permissions: Permission[];
      id: number;
      parent_id: number;
      is_checked: boolean;
      paths: string;
   }

   const permissionGroups = ref<PermissionGroup[]>([]);

   // 获取权限列表
   const getPermissionList = async () => {
      const res = await api.authority.getAuthOption({ role_id: String(currentNodeId.value) });
      if (res.code === 200) {
         // 直接使用原始数据结构，保留菜单的层级关系
         menuPermissions.value = res.data;
      }
   };
   onMounted(() => {
      getRoleList();
      getPermissionList();
   });
   // 模拟部门数据
   const departmentTree = ref([]);

   const handleSearch = () => {
      console.log("handleSearch");
      isSearch.value = true;
   };
   // 监听isSearch变化，当为true时自动获取焦点
   watch(isSearch, (newVal) => {
      if (newVal) {
         // 使用nextTick确保DOM更新后再获取焦点
         nextTick(() => {
            inputRef.value?.focus();
         });
      }
   });

   interface User {
      Sname: string;
      name: string;
      Sphone: string;
      Sposition: string;
      id: number;
   }
   interface Tree {
      label: string;
      children?: Tree[];
   }
   interface Tree {
      [key: string]: any;
   }

   const filterText = ref("");
   const treeRef = ref<TreeInstance>();

   const defaultProps = {
      children: "children",
      label: "label",
   };

   watch(filterText, (val) => {
      treeRef.value!.filter(val);
      // 当搜索框清空时，重置树的展开状态
      if (!val) {
         nextTick(() => {
            // 收起所有节点
            treeRef.value?.store.setData(departmentTree.value);
         });
      }
   });
   //watch(value,()=>{})
   //watchEffect(()=>{})
   const filterNode = (value: string, data: Tree) => {
      if (!value) return true;
      return data.name.includes(value);
   };
   // 当前点击的节点ID
   const currentNodeId = ref<number | null>(null);

   // 处理表格合并行或列的方法
   const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
      // 第一列（父级分组列）
      if (columnIndex === 0) {
         // 获取当前行的类型
         const currentType = row.type;

         // 计算同类型的行数
         const typeGroups = {};
         permissionGroups.value.forEach((group, index) => {
            if (!typeGroups[group.type]) {
               typeGroups[group.type] = {
                  count: 0,
                  startIndex: index,
               };
            }
            typeGroups[group.type].count++;
         });
         // 如果是该类型的第一行，则合并单元格
         if (typeGroups[currentType] && rowIndex === typeGroups[currentType].startIndex) {
            return {
               rowspan: typeGroups[currentType].count,
               colspan: 1,
            };
         } else {
            return {
               rowspan: 0,
               colspan: 0,
            };
         }
      }
   };

   // 节点编辑处理
   const handleEdit = (data: any) => {
      console.log("Edit node:", data);
   };

   const search = ref("");

   // 重构后的菜单权限数据结构
   const menuPermissions = ref<any[]>([]);
// ------------------过滤
   // 根据搜索关键字过滤菜单
   const filteredMenuPermissions = computed(() => {
      if (!search.value) return menuPermissions.value;

      return menuPermissions.value.filter((menu) => {
         // 检查一级菜单名称是否匹配
         if (menu.name && menu.name.includes(search.value)) return true;

         // 检查二级菜单名称是否匹配
         if (menu.children && menu.children.length > 0) {
            const hasMatchingSubmenu = menu.children.some((submenu) => submenu.name && submenu.name.includes(search.value));
            if (hasMatchingSubmenu) return true;

            // 检查三级菜单名称是否匹配
            const hasMatchingItem = menu.children.some(
               (submenu) => submenu.children && submenu.children.some((item) => item.name && item.name.includes(search.value))
            );
            if (hasMatchingItem) return true;
         }

         return false;
      });
   });
// -------------------------------------
   // 检查菜单是否全选
   const isMenuChecked = (menu: any) => {
      if (!menu.children || menu.children.length === 0) {
         return menu.is_checked === 1;
      }
      return menu.children.every((submenu: any) => isSubmenuChecked(submenu));
   };

   // 检查菜单是否部分选中
   const isMenuIndeterminate = (menu: any) => {
      if (!menu.children || menu.children.length === 0) {
         return false;
      }
      const hasChecked = menu.children.some((submenu: any) => isSubmenuChecked(submenu) || isSubmenuIndeterminate(submenu));
      const allChecked = menu.children.every((submenu: any) => isSubmenuChecked(submenu));
      return hasChecked && !allChecked;
   };

   // 处理菜单选择变化
   const handleMenuCheckChange = (checked: boolean, menu: any) => {
      if (!menu) return;

      // 设置当前菜单的选中状态
      menu.is_checked = checked ? 1 : 0;

      // 设置所有子菜单的选中状态
      if (menu.children && menu.children.length > 0) {
         menu.children.forEach((submenu: any) => {
            handleSubmenuCheckChange(checked, submenu);
         });
      }
   };

   // 检查子菜单是否全选
   const isSubmenuChecked = (submenu: any) => {
      // 如果子菜单没有children属性或children为空数组
      if (!submenu.children || submenu.children.length === 0) {
         // 直接返回子菜单自身的选中状态
         return submenu.is_checked === 1;
      }
      // 如果子菜单有children，则检查所有子项是否都被选中
      return submenu.children.every((item: any) => item.is_checked === 1);
   };

   // 检查子菜单是否部分选中
   const isSubmenuIndeterminate = (submenu: any) => {
      if (!submenu.children || submenu.children.length === 0) {
         return false;
      }
      const hasChecked = submenu.children.some((item: any) => item.is_checked === 1);
      const allChecked = submenu.children.every((item: any) => item.is_checked === 1);
      return hasChecked && !allChecked;
   };

   // 处理子菜单选择变化
   const handleSubmenuCheckChange = (checked: boolean, submenu: any) => {
      if (!submenu) return;

      // 设置当前子菜单的选中状态
      submenu.is_checked = checked ? 1 : 0;

      // 设置所有权限项的选中状态
      if (submenu.children && submenu.children.length > 0) {
         submenu.children.forEach((item: any) => {
            item.is_checked = checked ? 1 : 0;
         });
      }
   };

   // 处理权限项选择变化
   const handlePermissionItemChange = (submenu: any) => {
      if (!submenu || !submenu.children) return;

      // 更新子菜单的选中状态
      const allChecked = submenu.children.every((item: any) => item.is_checked === 1);
      const anyChecked = submenu.children.some((item: any) => item.is_checked === 1);

      // 设置子菜单的选中状态
      submenu.is_checked = allChecked ? 1 : anyChecked ? 1 : 0;
      
      // 查找并更新父级菜单的状态
      const updateParentMenu = () => {
         // 查找包含此子菜单的父级菜单
         const parentMenu = menuPermissions.value.find(menu => 
            menu.children && menu.children.some(sub => sub === submenu)
         );
         
         if (parentMenu) {
            // 检查父级菜单的所有子菜单是否都被选中
            const allSubmenusChecked = parentMenu.children.every(sub => 
               isSubmenuChecked(sub)
            );
            const anySubmenusChecked = parentMenu.children.some(sub => 
               isSubmenuChecked(sub) || isSubmenuIndeterminate(sub)
            );
            
            // 更新父级菜单的选中状态
            parentMenu.is_checked = allSubmenusChecked ? 1 : anySubmenusChecked ? 1 : 0;
         }
      };
      
      updateParentMenu();
   };

   // 全选功能
   const selectAll = () => {
      // 创建一个新的数组，以确保Vue能够检测到变化
      const newMenuPermissions = JSON.parse(JSON.stringify(menuPermissions.value));
      
      // 递归设置所有菜单项的选中状态
      const setAllChecked = (items: any[]) => {
         if (!items || items.length === 0) return;
         
         items.forEach((item) => {
            // 设置当前项为选中
            item.is_checked = 1;
            
            // 递归处理子项
            if (item.children && item.children.length > 0) {
               setAllChecked(item.children);
            }
         });
      };
      
      // 从顶层菜单开始递归设置
      setAllChecked(newMenuPermissions);
      
      // 替换原始数组，触发Vue的响应式更新
      menuPermissions.value = newMenuPermissions;
   };

   // 取消全选功能
   const unselectAll = () => {
      // 创建一个新的数组，以确保Vue能够检测到变化
      const newMenuPermissions = JSON.parse(JSON.stringify(menuPermissions.value));
      
      // 递归设置所有菜单项的未选中状态
      const setAllUnchecked = (items: any[]) => {
         if (!items || items.length === 0) return;
         
         items.forEach((item) => {
            // 设置当前项为未选中
            item.is_checked = 0;
            
            // 递归处理子项
            if (item.children && item.children.length > 0) {
               setAllUnchecked(item.children);
            }
         });
      };
      
      // 从顶层菜单开始递归设置
      setAllUnchecked(newMenuPermissions);
      
      // 替换原始数组，触发Vue的响应式更新
      menuPermissions.value = newMenuPermissions;
   };

   // 保存权限设置
   const savePermissions = async () => {
      if (!currentNode.value) {
         ElMessage.error("请先选择角色");
         return;
      }

      // 收集所有选中的权限
      const selectedAuthCodes: string[] = [];

      // 递归函数收集权限码
      const collectAuthCodes = (items: any[]) => {
         items.forEach((item) => {
            if (item.is_checked === 1) {
               selectedAuthCodes.push(item.auth_code);
            }

            if (item.children && item.children.length > 0) {
               collectAuthCodes(item.children);
            }
         });
      };

      collectAuthCodes(menuPermissions.value);

      const params = {
         id: currentNode.value.id,
         name: currentNode.value.name,
         auth_codes: JSON.stringify(selectedAuthCodes),
         status: "1",
      };

      const res = await api.authority.editRole(params);
      if (res.code === 200) {
         ElMessage.success("权限设置已保存");
      } else {
         ElMessage.error("权限设置保存失败");
      }
   };

   // 按类型分组的权限数据
   interface GroupedPermissions {
      [key: number]: PermissionGroup[];
   }

   const groupedPermissions = computed(() => {
      const groups: GroupedPermissions = {};
      permissionGroups.value.forEach((item) => {
         if (!groups[item.type]) {
            groups[item.type] = [];
         }
         groups[item.type].push(item);
      });
      return Object.values(groups);
   });

   // 处理添加角色
   const handleAddRole = () => {
      newRoleRef.value.openLoading(0);
   };
</script>

<style scoped>
   html,
   body,
   #app {
      height: 100%;
      margin: 0;
   }

   .container {
      height: 80vh;
      width: 100vw;
      display: flex;
      flex-direction: column;
      box-sizing: border-box;
   }

   .full-height-row {
      flex: 1;
      min-height: 0;
   }

   .full-height-col-left {
      display: flex;
      flex-direction: column;
      height: 100%;
   }

   .full-height-col-left .full-height-card :deep(.el-card__body) {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 10px;
      background: #f5f8fd;
   }
   .right-container-title {
      background: #fff;
      position: fixed;
      top: 65px;
      z-index: 10;
      display: flex;
      height: 60px;
      width: 78%;
      justify-content: space-between;
      align-items: center;
   }
   .full-height-col-right {
      display: flex;
      flex-direction: column;
      height: 100%;
      margin-top: 20px;
   }

   .full-height-card {
      flex: 1;
      display: flex;
      flex-direction: column;
   }

   .full-height-card :deep(.el-card__body) {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 10px;
   }

   :deep(.el-tree-node.is-current > .el-tree-node__content .custom-tree-node span) {
      color: #8272ff;
   }
   :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
      background-color: #6860ff;
      border-color: #6860ff;
   }
   :deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
      background-color: #6860ff;
      border-color: #6860ff;
   }
   :deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
      color: #606266;
   }
   .full-height-tree {
      flex: 1;
      overflow: auto;
   }

   .empty-tip {
      color: #999;
      text-align: center;
      padding: 40px 0;
   }

   .mb-4 {
      margin-bottom: 1rem;
   }

   .button-container {
      padding: 0 0px;
      display: flex;
      justify-content: space-between;
   }

   .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-right: 8px;
   }

   .operation-icons {
      display: inline-flex !important;
      margin-left: 10px;
      gap: 8px;
   }

   .custom-icon {
      font-size: 16px;
      color: #409eff;
      cursor: pointer;
   }

   .custom-icon:hover {
      color: #66b1ff;
   }

   @keyframes rotate-animation {
      from {
         transform: rotate(0deg);
      }
      to {
         transform: rotate(360deg);
      }
   }

   .rotate {
      animation: rotate-animation 0.5s linear;
   }

   .node-tools {
      transition: transform 0.3s ease;
   }

   :deep(.el-tree-node__content) {
      height: 32px;
   }

   :deep(.title-bar) {
      background: none;
      padding: 0px;
   }

   :deep(.el-card) {
      border: none;
   }
   /* 权限表格样式 */
   .permission-table {
      border-collapse: collapse;
      width: 100%;
   }

   .permission-section {
      margin-bottom: 20px;
      border: 1px solid #ebeef5;
      border-radius: 4px;
      background-color: #fff;
   }

   .menu-header {
      padding: 12px 20px;
      background-color: #f5f7fa;
      border-bottom: 1px solid #ebeef5;
      font-weight: bold;
   }

   .submenu-container {
      padding: 0;
   }

   .submenu-item {
      margin: 0;
      padding: 10px 20px;
      border-bottom: 1px solid #ebeef5;
   }

   .submenu-item:last-child {
      border-bottom: none;
   }

   .submenu-checkbox {
      font-weight: 500;
   }

   .permission-items {
      display: flex;
      flex-wrap: wrap;
      margin-top: 10px;
      margin-left: 25px;
      padding: 5px 0;
      border-top: 1px dashed #ebeef5;
   }

   .permission-item-checkbox {
      margin-right: 20px;
      margin-bottom: 10px;
      min-width: 120px;
   }

   /* 表格形式的权限选择样式 */
   .submenu-container {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      padding: 8px 0;
   }

   .submenu-checkbox {
      margin-right: 15px;
      margin-bottom: 8px;
   }

   .permission-container {
      display: flex;
      flex-direction: column;
      padding: 8px 0;
   }

   .permission-group {
      margin-bottom: 8px;
      padding-bottom: 8px;
      border-bottom: 1px dashed #ebeef5;
   }

   .permission-group:last-child {
      border-bottom: none;
      margin-bottom: 0;
      padding-bottom: 0;
   }

   .permission-items {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
   }

   .permission-checkbox {
      margin-right: 15px;
      margin-bottom: 8px;
   }

   :deep(.el-table) {
      --el-table-border-color: #ebeef5;
      --el-table-header-bg-color: #f5f7fa;
   }

   :deep(.el-table__header) {
      font-weight: bold;
   }

   :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
      background-color: #6860ff;
      border-color: #6860ff;
   }

   :deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
      background-color: #6860ff;
      border-color: #6860ff;
   }
</style>
